import React, { Component } from 'react'
import Child from './Child'

export default class Father extends Component {
  state = {
    msg: 'Hi',
    flag: true,
    num: 0
  }
  constructor() {
    super()
    console.log('父组件-constructor')
  }
  componentDidMount() {
    console.log('父组件-componentDidMount')
  }
  componentDidUpdate() {
    console.log('父组件-componentDidUpdate')
  }
  setMsg = () => {
    this.setState({
      msg: 'Hi ' + Math.random()
    })
  }
  tabChild = () => {
    const flag = !this.state.flag
    this.setState({
      flag
    })
  }
  setNum = () => {
    this.setState({
      num: Math.random()
    })
  }
  render() {
    console.log('父组件-render')
    const {msg, flag} = this.state

    // 条件渲染
    // const dom = flag && <Child msg={msg} />
    // const dom = flag ? <Child msg={msg} /> : null
    let dom
    if(flag) {
      dom = <Child msg={msg} />
    } else {
      dom = null
    }

    return (
      <div className='father'>
        <span>父组件当前状态值：{msg}</span>
        <button onClick={this.setMsg}>父组件自己修改数据</button>
        <button onClick={this.setNum}>修改num</button>
        <button onClick={this.tabChild}>切换子组件</button>
        {dom}
      </div>
    )
  }
}
